import { Component } from 'react';
import { connect } from 'dva';
import { updateState } from '../../../models/global';
import { Icon,InputGroup,Tree,Tooltip,Divider,Popover,MenuItem,Menu, Spinner } from '@blueprintjs/core';
import { ajax_post,ajax_get } from '../../../api/ajax';
import {trim, cloneJson} from '../../../utils/util';
import ScrollWrapper from '../../../components/ScrollWrapper';
import styles from './AreaList.less';
import * as turf from '@turf/turf';

class AreaList extends Component {
    constructor(props) {
        super(props);
		this.state = {
      firstLoad: false,
			clicked: false,
			num: 11,
			filterValue: "",
			filterKey: '',
			country: [],
			screet: null,
			nodes: [],
			currentStreet: "", //选中的街道
		}
    }

	handleNodeClick = (nodeData, nodePath, e) => {
		// const {type} = nodeData.nodeData;
		e.preventDefault();
		e.stopPropagation();
		const {id, label, isExpanded} = nodeData;
		const {type, countryName} = nodeData.nodeData;
		// 行政区
		if(type === 'area') {
			if(!isExpanded) {
				this.handleNodeExpand(nodeData);
			} else {
				this.handleNodeCollapse(nodeData);
			}
			this.props.SetSettingParams({
				id,
				type
			});
			this.props.SetSettingName(id, countryName || id);
      this.showBoundary({name: nodeData.id, type: nodeData.nodeData.type, showLayer: true})
			return;
		} else {
			// if(nodeData.id.indexOf("本级") < 0) {
				this.showBoundary({name: nodeData.id, type: nodeData.nodeData.type, showLayer: true})
			// }
			this.props.SetSettingParams({
				id,
				type
			});
			this.props.SetSettingName(id, countryName || id);
		}

		// if(type === 'street') {
		// }
		// const _this = this;
		// let Dom;
		// if(e.target.parentElement && e.target.parentElement.children &&
		// 	e.target.parentElement.children[0] && e.target.parentElement.children[0].className &&
		// 	e.target.parentElement.children[0].className.length &&
		// 	e.target.parentElement.children[0].className.indexOf("bp3-icon") > -1) {
		// 	Dom = e.target.parentElement.children[0];
		// }
		// setTimeout(() => {
		// 	_this.setState({clicked:false})
		// },1000);
		// setTimeout(() => {
		// 	if(_this.state.clicked) return;
		// 	if(Dom) {
		// 		Dom.click();
		// 	}
		// },200);

    };

	SetSettingName = (name) => {
		this.props.SetSettingName(name)
	}

	handleNodeDoubleClick = (nodeData, nodePath, e) => {
		if(e) {
			e.preventDefault();
			e.stopPropagation();
		}
		const {id, label, isExpanded} = nodeData;
		const {type, countryName} = nodeData.nodeData;
		// if(type === 'area') {
		// 	if(!isExpanded) {
		// 		this.handleNodeExpand(nodeData);
		// 	} else {
		// 		this.handleNodeCollapse(nodeData);
		// 	}
		// 	return;
		// }
		this.setState({clicked:true});
		this.props.SetSettingName(id, countryName || id);
		this.props.handleTabChange("setting", id, type);
	}

    handleNodeCollapse = (nodeData, nodePath, e) => {
		const name = nodeData.id;
		const {country} = this.state;
		country.forEach((ct) => {
			if(ct.name === name) {
				ct.isExpanded = false;
			}
		});
		this.setState({country});
		this.updateTreeNodes(country);
    };

    handleNodeExpand = (nodeData, nodePath, e) => {
		const {country} = this.state;
		const name = nodeData.id;
		country.forEach((ct) => {
			if(ct.name === name) {
				if(ct.streets && ct.streets.length > 0) {
					ct.isExpanded = true;
					this.setState({country});
					this.updateFilterKey();
					// this.updateTreeNodes(country);
				} else {
					this.queryScreet(name, true);
				}
				return;
			}
		});
    };

	forEachNode = (nodes, callback) => {
        if (nodes == null) {
            return;
        }

        for (const node of nodes) {
            callback(node);
            this.forEachNode(node.childNodes, callback);
        }
    }

	handleFilterChange = (e) => {
		this.setState({
			filterValue: e.target.value
		})
	}

	//定位行政或者街道
	position = ({name, type, target}) => {
		if(!name || !type) return;
		if(type === 'area') {
			const {map} = this.props;
			const multiPolygon = turf.multiPolygon(target.coordinates);
			const bbox = turf.bbox(multiPolygon);
			const bounds = new atlas.LngLatBounds([bbox[0], bbox[1]], [bbox[2], bbox[3]]);
			map.fitBounds(bounds);
		}
	}

	//显示行政边界
	showBoundary = ({name, showLayer}) => {
		const {map,setSelectedFeature} = this.props;
		// area 区, street 街道
		if(map) {
			ajax_get({
				url: `/dm/tree/${name}/`
			}).then((res) => {
				if(!res || !res.data) return;
				try {
					let result = res.data[0];
          // 加载属性面板
          setSelectedFeature && setSelectedFeature(result);
					result = JSON.parse(result.geom);
					if(showLayer) {
						const target = {
							type: 'Feature',
							geometry: result,
						};
						const sourceId = `dmdz-source-area-${name}`;
						const source = map.getSource(sourceId);
						if(!source) {
							map.addSource(sourceId, {
								type: 'geojson',
								data: {
									type: 'FeatureCollection',
									features: [target]
								}
							});
						} else {
							source.setData({
								type: 'FeatureCollection',
								features: [target]
							});
						}
						const layerId = `dmdz-layer-street-${name}`;
						if(map.getLayer(layerId)) {
							map.removeLayer(layerId);
						}
						map.addLayer({
							id: layerId,
							type: 'line',
							source: sourceId,
							paint: {
								"line-color": "#f00",
								"line-width": 4,
								"line-dasharray": [2, 2]
							}
						});
					}
					this.position({name, type: 'area', target: result});
				} catch {

				}
			})
		}
	}

	/**
	 * 查询城市区域与街道列表
	 */
	queryCountry = () => {
		const {countryDataset} = this.props;
		ajax_get({
			url:`/dm/tree/`,
			data: {level:0, type: "districts"}
		}).then((res)=>{
			if(!res || !res.data) {
				this.setState({country: [], nodes: []});
				return;
			}
			// 设置城市全局行政边界
			// updateState({countryGeometry: res.data});
			let country = [];
			res.data.map(item => {
				country.push({name: item.name, code: item.code, streets: []});
			});
			this.setState({country});
			this.updateTreeNodes(country);
		}).catch((data)=>{
			this.setState({country: [], nodes: []});
		})
	}

	/**
	 * 生成树节点
	 */
	getNode = ({name, isExpanded, nodeData, childNodes, icon, hasCaret}) => {
		const type = nodeData && nodeData.type;
		const isBaseArea = name.indexOf("本级") >= 0;
		const menu = (<Menu>
			{<MenuItem onClick={(e) => this.showBoundary({name, type: nodeData.type})} icon="locate" text="定位" /> }
			{
				<MenuItem onClick={(e) => this.showBoundary({name, type: nodeData.type, showLayer: true})} icon="map" text="显示行政边界" />
			}
			{type === 'street' && <MenuItem onClick={(e) => {
				const t = {id:name, label:name, nodeData};
				this.handleNodeDoubleClick(t);
			}} icon="properties" text="基础地名列表" />}
		</Menu>);
		return {
			id: name,
			label: name,
			hasCaret,
			isExpanded,
			icon: icon,
			nodeData: nodeData || {},
			secondaryLabel: (
				<Popover content={menu} position="right">
					<Icon icon="more" style={{cursor: 'pointer'}} />
				</Popover>
			),
			childNodes
		}
	}

	/**
	 * 更新树节点
	 */
	updateTreeNodes = (_country) => {
		const country = _country || this.state.country;
		const nodes = country.map((ct) => {
			const {name, code, streets, isExpanded} = ct;
			const childNodes = (streets || []).map((street) => {
				return this.getNode({
					name: street.name,
					icon: 'grid',
					nodeData: {
						type: 'street',
						code: street.code,
						countryName: name,
						countryCode: code,
					},
				});
			});
			return this.getNode({
				name,
				isExpanded,
				icon: isExpanded ? "folder-open" : "folder-close",
				childNodes,
				hasCaret: true,
				nodeData: {
					type: 'area',
					code
				}
			})
		});
		this.setState({nodes});
	}

	/**
	 * 查询街道
	 */
	queryScreet = (countryName, setExpanded) => {
		const {streetDataset} = this.props;
		console.log(countryName)
		ajax_get({
			url: `/dm/tree/`,
			data: {level: countryName === '市本级' ? 1 : 0, type: "streets", name: countryName},
		}).then((res)=>{
			if(!res || !res.data) return;
			const {country} = this.state;
			country.forEach((ct) => {
				if(countryName === ct.name) {
					ct.streets = res.data.map(d => d);
					if(setExpanded) {
						ct.isExpanded = true;
					}
				}
			});
			this.setState({country});
			this.updateFilterKey();
		}).catch((res)=>{

		})
	}

    componentWillMount() {
        this.queryCountry();
	}

	/**
	 * 更新过滤关键词
	 */
	updateFilterKey = (e) => {
		let filterKey = this.state.filterKey;
		if(e && e.target.value !== undefined) {
			filterKey = e.target.value;
			this.setState({filterKey});
		}
		const country = cloneJson(this.state.country);
		if(trim(filterKey).length >= 1) {
			country.forEach((ct) => {
				ct.streets = ct.streets.filter(street => {return street.indexOf(filterKey) >= 0;});
			});
		}
		this.updateTreeNodes(country);
	}

    render() {
		const {nodes} = this.state;
        return (
			<div className={styles.main}>
				<div>
					{/* <InputGroup
						className="bp3-right bp3-fill"
						leftIcon="filter"
						onChange={this.updateFilterKey}
						placeholder="输入关键词过滤"
						value={this.state.filterKey}
					/> */}
					<Divider />
				</div>
				<div>
					<ScrollWrapper className={styles.scroll}>
						<div>
							{
								<Tree
									contents={nodes}
									ref="tree"
									onNodeClick={this.handleNodeClick}
									onNodeDoubleClick={this.handleNodeDoubleClick}
									onNodeCollapse={this.handleNodeCollapse}
									onNodeExpand={this.handleNodeExpand}
								/>
							}
							{
								nodes.length === 0 && <div style={{marginTop: 50}}><Spinner /></div>
							}
						</div>
					</ScrollWrapper>
				</div>
			</div>
        )
    }
}

function mapStateToProps(state) {
    return {
		countryGeometry: state.map.countryGeometry,
		map: state.map.map,
		countryDataset: state.map.countryDataset,
		streetDataset: state.map.streetDataset
    };
}

export default connect(mapStateToProps)(AreaList);
